<template>
    <template v-for="(item, index) in btnData" :key="item.BtnMark">
        <a :btnMark="item.BtnMark" :style="item.BtnStyle" @click="handleMenuClick(item.BtnMethod)"
           :title="item.Name" v-bind="item.BtnAttr ? { [item.BtnAttr]: true } : {}">
            {{ item.Name }}
        </a>
        <a-divider v-if="index < btnData.length - 1" type="vertical" />
    </template>

    <template v-for="(node, index) in filteredButtonSlots" :key="index">
        <div v-if="node.type" class="filtered-button">
            <component :is="node" v-bind="{
                ...node.props,
                disabled: node.props?.btnMark ? shouldDisableButton(node.props.btnMark) : false
            }" v-on="node.props?.on || {}" />
            <a-divider v-if="index < filteredButtonSlots.length - 1" type="vertical" />
        </div>
    </template>
</template>

<script lang="ts" setup>
import { inject, ref, useSlots, onMounted, getCurrentInstance } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { getPageLinkBtnData } from '@/api/syssetting/menu';
import { notification, message } from 'ant-design-vue';
//import { MenuInput } from '@/type/syssetting/menu';

// 全局缓存对象
if(!window.btnDataCache){
window.btnDataCache = new Map<string, Promise<any>>();
}

const props = defineProps({
    // ... 其他props
    record: {
        type: Object,
        default: () => ({})
    }
});

const route = useRoute();
const router = useRouter();
const slots = useSlots();
const btnData = ref([]);

// 用于存储过滤后的按钮插槽节点
const filteredButtonSlots = ref([]);

const parentMethods = inject('parentMethods');

const handleMenuClick = (funcname) => {
    debugger
    if(props.record){
        parentMethods[funcname]?.(null,props.record);
    }else{
        arentMethods[funcname]?.();
    }
};

// 添加一个方法来检查按钮是否需要禁用
const shouldDisableButton = (btnMark) => {
    const btnItem = btnRemoveDatas.find(item => item.BtnMark === btnMark);
    return btnItem?.SingleSelected && props.selectedRowKeys.length !== 1;
};

let btnRemoveDatas:any[] = [];
let btnDatas:any[] = [];

onMounted(async() => {
    let path = route.path; 
     // 如果缓存中没有该路径的请求，创建并缓存
    if (!window.btnDataCache.has(path)) {
        window.btnDataCache.set(path, fetchBtnData(path));
    }
    
    // 等待缓存的数据
    const data = await window.btnDataCache.get(path);
    renderData(data); 
    // if(btnDatas.length > 0){
    //     renderData(btnDatas);
    //     return;
    // } 
    // getPageLinkBtnData({ PagePath: path }).then((res) => {
    //     btnDatas = res.data.Data;
    //     isLoadData = true;
    //    renderData(btnDatas);
    // }).catch((err) => {
    //     console.log("获取菜单发生错误" + err);
    //     message.error("获取菜单发生错误" + err);
    // });

})

const fetchBtnData = async (path: string) => {
    try {
        const res = await getPageLinkBtnData({ PagePath: path });
        return res.data.Data;
    } catch (err) {
        console.error("获取菜单发生错误", err);
        message.error("获取菜单发生错误");
        return [];
    }
};

const renderData = (btnDatas:any) => {
     let oriBtnDatas = btnDatas
        const buttonSlot = slots.button;
        // 将 btnDatas 中的 BtnMark 存储到 Set 中，方便快速查找
        const validBtnMarks = new Set(btnDatas.map(item => item.BtnMark));
        if (buttonSlot) {
            const vNodes = buttonSlot();
            // 过滤出 btnMark 存在于 validBtnMarks 中的节点
            filteredButtonSlots.value = vNodes.filter(node => {
                if (node.props && node.props.btnMark) {
                    return validBtnMarks.has(node.props.btnMark);
                }
                return false;
            });
            // 递归函数用于遍历 VNode 树
            const traverseVNodes = (nodes) => {
                nodes.forEach((node) => {
                    if (node.type.name === 'AButton' || (node.props && node.props.tag === 'AButton')) {

                        if (btnDatas && node.props.btnMark) {
                            btnDatas = btnDatas.filter((item) => item.BtnMark !== node.props.btnMark);
                        }
                    }
                    if (node.children && Array.isArray(node.children)) {
                        traverseVNodes(node.children);
                    }
                });
            };
            traverseVNodes(vNodes);
        }
        btnData.value = btnDatas;
        btnRemoveDatas = oriBtnDatas.filter(item => !btnDatas.some(btnItem => btnItem.BtnMark === item.BtnMark));
}

</script>
